package com.example.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 读取配置文件
 */
@Slf4j
public class ConfigUtil {
    private static Map<String, String> paramMap = new HashMap<>();

    static {
        try (BufferedReader br = ResourceUtil.getUtf8Reader("app.prop")) {
            String line;
            while ((line = br.readLine()) != null) {
                String trim = line.trim();
                if (StrUtil.isBlank(trim) || trim.startsWith("#")) {
                    continue;
                }
                int i = trim.indexOf("=");
                if (i < 1) {
                    throw new RuntimeException("配置不对，没找到=符号");
                }
                String param = trim.substring(0, i).trim();
                String value = trim.substring(i + 1).trim();
                if (StrUtil.isBlank(param) || StrUtil.isBlank(value)) {
                    throw new RuntimeException("配置为空");
                }
                paramMap.put(param, value);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 读取带前缀的配置
     *
     * @param prefix
     * @return
     */
    public static <T> T getConfig(String prefix, Class<T> clazz) {
        T bean = ReflectUtil.newInstance(clazz);
        //过滤
        Map<String, String> map = new HashMap<>();
        paramMap.forEach((key, value)->{
            if(key.startsWith(prefix)) {
                map.put(key.substring(prefix.length()+1), value);
            }
        });
        //填充参数
        BeanUtil.fillBeanWithMap(map, bean, true,   // 忽略大小写
                CopyOptions.create()
                        .setIgnoreCase(true)         // key 忽略大小写
                        .setIgnoreError(true));
        return bean;
    }

    /**
     * 自动获取注解
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getConfig(Class<T> clazz) {
        return getConfig("", clazz);
    }
}
